from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from user import models,userser
import re
from django.db.models import Q
from utils.jwttool import tooljwt
from utils.tecent import TencentCloudAPI
import random
from utils.sendmsg import send_message
import json
from utils.myredis import redistoll
from .tasks import add,send
# Create your views here.
#密码登录
class Loginpwd(APIView):
  def post(self,request):
      # api = TencentCloudAPI()
      # result = api.captcha(
      #     request.data.get("ticket"),
      #     request.data.get("randstr"),
      #     request._request.META.get("REMOTE_ADDR"),
      # )
      #return Response(result)
      account = request.data.get("account")
      password = request.data.get("password")
      #验证account为邮箱
      info=models.UserModel.objects.filter(Q(username=account)|Q(email=account)|Q(phone=account)).first()
      if info is None:
        return Response({"code": 400, "msg": "账号不存在"})
      elif info.password == password:
        data={
            "id":info.id,
            "account":account,
            "token":tooljwt.getToken(info.id,account)
        }
        if info.headimg:
          data["headimg"]=info.headimg
        else:
          data["headimg"]="/uploads/avatar/2012/default.jpg"
        return Response({"code": 200, "msg": "登录成功","data":data})
      else:
        return Response({"code": 400, "msg": "密码错误"})

#验证码发送接口
class SendCode(APIView):
    def post(self,request):
        phone = request.data.get("phone")#必须加一个正则正则 是手机号才能发送
        code=str(random.randint(1000,9999))#随机的四位数字
        #result=send_message(phone,code)#返回的是序列话的json字符串
        #查看redis中是否存在这个手机号  如果存在说明刚才发了 还没过期 给用户提示
        #如果不存在说明 没发过 然后异步调用发送短信  短信的错误 在异步函数那处理
        rediscode=redistoll.getstr(phone)
        if rediscode:
            return Response({"code": 400, "msg": "请勿重复发送"})
        else:
            send.delay(phone,code)
            redistoll.setstr(phone,code,60*2)#设置过期时间5分钟
            return Response({"code": 200, "msg": "发送成功"})


#登录接口
class Login(APIView):
    def post(self,request):
        account = str(request.data.get("account"))
        code=request.data.get("code")
        rediscode=redistoll.getstr(account)
        print(code,rediscode)
        if code != rediscode:
            return Response({"code": 400, "msg": "验证码错误"})
        #查询用户是否存在
        info=models.UserModel.objects.filter(phone=account,isshow=1).first()
        #设置返回的data
        if info is None:
            #创建用户
            newdata=models.UserModel.objects.create(phone=account)
            token=tooljwt.getToken(newdata.id,newdata.phone)
            id=newdata.id
            return Response({"code": 200, "msg": "登录成功", "data": {"token": token, "id": id, "account": account}})
        token=tooljwt.getToken(info.id,info.phone)
        id=info.id
        return Response({"code": 200, "msg": "登录成功","data":{"token":token,"id":id,"account":account}})

#注册
class  Register(APIView):
    def post(self,request):
        code=request.data.get("code")
        account=request.data.get("account")
        password=request.data.get("password")
        rediscode = redistoll.getstr(account)
        data={}
        if re.match(r"^1[3-9]\d{9}$", account) and code is None:
            return Response({"code": 400, "msg": "请输入验证码"})
        if re.match(r"^1[3-9]\d{9}$", account) and code!=rediscode:
            return Response({"code": 400, "msg": "验证码错误"})
        #一系列判断当前的账号是什么
        if re.match(r"^1[3-9]\d{9}$", account):
            data["phone"]=account
        elif re.match(r"^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", account):
            data["email"]=account
        else:
            data["username"]=account
        data["password"]=password
        ser=userser.UserSerializer(data=data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200, "msg": "注册成功","data": ser.data})
        return Response({"code": 400, "msg": "注册失败","data":ser.errors})


class CheckPhone(APIView):
    def get(self,request):
        phone=request.query_params.get("phone")
        info=models.UserModel.objects.filter(phone=phone).first()
        if info:
            return Response({"code": 400, "msg": "手机号已存在"})
        return Response({"code": 200, "msg": "手机号可用"})

from .tasks import add
class TestUser(APIView):
    def post(self,request):
        sum_ = add.delay(1, 2)#异步任务的调用  通过delay
        print(sum_.get())
        return Response({"code": 200, "msg": "测试成功"})
from utils.authorization import MyAuthentication

class Cart(APIView):
    #给接口设置token访问权限
    authentication_classes = [MyAuthentication]
    def get(self,request):
        return Response({"code": 200, "msg": "购物车"})
